
// 自定义指令，用于处理滚动动画
export const scrollAnimate = {
    mounted(el, binding) {
        // 设置初始状态为隐藏
        el.style.opacity = '0';

        // 获取指令参数
        let animation = 'fadeIn';
        let delay = 0;
        let duration = 1000; // 默认动画持续时间为1秒
        let repeat = false;

        if (typeof binding.value === 'string') {
            animation = binding.value;
        } else if (binding.value) {
            animation = binding.value.animation || animation;
            delay = binding.value.delay || delay;
            duration = binding.value.duration || duration;
            repeat = binding.value.repeat || repeat;
        }

        // 创建观察器实例
        const observer = new IntersectionObserver(
            (entries) => {
                entries.forEach((entry) => {
                    if (entry.isIntersecting) {
                        // 元素进入视口时添加动画
                        el.style.opacity = '1';
                        el.classList.add('animate__animated', `animate__${animation}`);
                        el.style.animationDuration = `${duration}ms`;
                        el.style.animationDelay = `${delay}ms`;

                        if (repeat) {
                            el.style.animationIterationCount = 'infinite';
                        }

                        // 只触发一次动画
                        observer.unobserve(el);
                    }
                });
            },
            { threshold: 0.1 } // 元素可见度达到10%时触发
        );

        // 开始观察目标元素
        observer.observe(el);
    },

    beforeUnmount(el) {
        // 清除观察器
        const observers = IntersectionObserver._observers || [];
        observers.forEach((observer) => {
            observer.unobserve(el);
        });

        // 移除动画类
        el.classList.remove('animate__animated', ...el.classList
            .value
            .split(' ')
            .filter(className => className.startsWith('animate__')));
    }
};

export default scrollAnimate;